//
//  AppDelegate.m
//  Zaker
//
//  Created by 赵磊 on 16/3/7.
//  Copy right © 2016年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "PchFile.pch"
#import "JPUSHService.h"
#import <CoreLocation/CoreLocation.h>
#import "GuideViewController.h"
#import <TencentOpenAPI/TencentOAuth.h>
@interface AppDelegate ()<WXApiDelegate, CLLocationManagerDelegate>

@property(nonatomic ,copy)NSString *strTitle;
@property (nonatomic, retain) CLLocationManager *locationManager; //定位城市

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    [self locate];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([userDefault objectForKey:@"isFirst"] == nil) {
        GuideViewController *guideVC = [[GuideViewController alloc] init];
        _window.rootViewController = guideVC;
        [userDefault setObject:@"已经启动过程序了" forKey:@"isFirst"];
        NSLog(@"第一次启动程序");
    }else
    {
    // 新闻页面创建
    NewsViewController *newsVC = [[NewsViewController alloc] init];
    UINavigationController *newsNavi = [[UINavigationController alloc] initWithRootViewController:newsVC];
    newsVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"新闻" image:[UIImage imageNamed:@"xinwen"] tag:1000];
    // 视听页面创建
    SeeViewController *seeVC = [[SeeViewController alloc] init];
    UINavigationController *seeNavi = [[UINavigationController alloc] initWithRootViewController:seeVC];
    seeVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"视听" image:[UIImage imageNamed:@"shipin"] tag:1100];
    // 搞笑页面创建
    FunnyViewController *funnyVC = [[FunnyViewController alloc] init];
    UINavigationController *funnyNavi = [[UINavigationController alloc] initWithRootViewController:funnyVC];
    funnyVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"玩乐" image:[UIImage imageNamed:@"gaoxiao"] tag:1200];
    // 社区页面创建
    CommunityViewController *communityVC = [[CommunityViewController alloc] init];
    UINavigationController *communityNavi = [[UINavigationController alloc] initWithRootViewController:communityVC];
    communityVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"社区" image:[UIImage imageNamed:@"shequ"] tag:1300];
    //我的页面
    MyViewController *my = [[MyViewController alloc] init];
    UINavigationController *navi4 = [[UINavigationController alloc] initWithRootViewController:my];
    navi4.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-wode"] tag:1000];
    // 创建tabBar
    self.tabBarController = [[UITabBarController alloc] init];
    _tabBarController.tabBar.barStyle = UIBarStyleDefault;
    _tabBarController.tabBar.tintColor = [UIColor redColor];
    // 将Controller放入tabBar中
    _tabBarController.viewControllers = @[newsNavi, seeNavi, funnyNavi, communityNavi, navi4];
    // 将windows的根视图设置为tabbarController
    self.window.rootViewController = _tabBarController;
    
    [WXApi registerApp:@"wx3762619f61c7c355"];
    
    
    /**<  极光推送 */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 0.8 ) {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    }else {
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    // Required
    //如需兼容旧版本的方式，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    [JPUSHService setupWithOption:launchOptions appKey:@"ce856bc43aa0a5348f2b6f06" channel:nil apsForProduction:NO];
    }
    return YES;
}

#pragma mark - 定位
- (void)locate{
    NSLog(@"111");
    // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        //定位初始化
        _locationManager=[[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        _locationManager.distanceFilter=10;
        [_locationManager startUpdatingLocation];//开启定位
    }else {
        //提示用户无法进行定位操作
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    // 开始定位
    [_locationManager startUpdatingLocation];
}

#pragma mark - CoreLocation Delegate

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    NSLog(@"11111fwrgjishg");
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         NSLog(@"%@", array);
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //NSLog(@%@,placemark.name);//具体位置
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             //cityName = city;
             NSLog(@"_______定位完成:%@",city);
             //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
             [manager stopUpdatingLocation];
         }else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"%@",deviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    // 微信 || qq
    return [WXApi handleOpenURL:url delegate:self] ||  [TencentOAuth HandleOpenURL:url];
    
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    // 微信 || qq
    return [WXApi handleOpenURL:url delegate:self] ||  [TencentOAuth HandleOpenURL:url];
}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
        
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n", msg.title, msg.description, obj.extInfo];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        //        [alert release];
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        //        [alert release];
    }
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {        if (resp.errCode == 0) {
            _strTitle = @"发送成功";
        }else if (resp.errCode == -1){
            _strTitle = @"发送失败";
        }else if (resp.errCode == -2){
            _strTitle = @"取消发送成功";
        }else if (resp.errCode == -3){
            _strTitle = @"发送失败";
        }else if(resp.errCode == -4){
            _strTitle = @"授权失败";
        }else if (resp.errCode == -5){
            _strTitle = @"微信不支持";
        }
        
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:_strTitle message:nil delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
